/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年8月15日
 */
package com.massyframework.beanskin.maven.plugin;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

/**
 * 模块登记Mojo
 * @author huangkh
 *
 */
@Mojo(name ="registration", defaultPhase = LifecyclePhase.COMPILE)
public class RegistrationMojo extends AbstractMojo {

	/**
     * POM
     */
    @Parameter( defaultValue = "${project}", readonly = true, required = true )
    private MavenProject project;
    
	/**
	 * 
	 */
	public RegistrationMojo() {
	}

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		MavenProject root = this.retrieveRootProject(this.project);
		
		//.beanskin目录
		File beanskinDir = new File(root.getBuild().getDirectory(), ".modules");
		if (!beanskinDir.exists()) {
			beanskinDir.mkdirs();
		}
		
		File projectFile = new File(beanskinDir, this.getFileName());
		if (projectFile.exists()) {
			projectFile.delete();
		}
		
		FileWriter writer = null;
		BufferedWriter bw = null;
		try {
			writer = new FileWriter(projectFile);
			bw = new BufferedWriter(writer);
			bw.write(this.project.getBasedir().getPath());
			
			this.getLog().info("registration module finished.");
		}catch(Exception e) {
			throw new MojoExecutionException(e.getMessage(), e);
		}finally {
			if (bw != null) {
				try {
					bw.close();
				}catch(Exception e) {
					
				}
			}
			if (writer != null) {
				try {
					writer.close();
				}catch(Exception e) {
					
				}
			}
		}
	}
	
	protected String getFileName() {
		return this.project.getGroupId().concat("_").concat(this.project.getArtifactId()).concat("_").concat(this.project.getVersion());
	}
	
	/**
	 * 采用递归方式，取回根maven项目
	 * @param project {@link MavenProject}
	 * @return {@link MavenProject}
	 */
	protected MavenProject retrieveRootProject(MavenProject project) {
		MavenProject parent = project.getParent();
		if (parent == null) return project;
		
		return this.retrieveRootProject(parent);
	}

}
